package com.wyj.utils

import android.text.TextUtils
import java.util.regex.Pattern

/**
 * 移除文本中的HTML标签
 */
object HtmlUtil {
    @JvmStatic
    private val regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>" // 定义script的正则表达式

    @JvmStatic
    private val regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>" // 定义style的正则表达式

    @JvmStatic
    private val regEx_html = "<[^>]+>" // 定义HTML标签的正则表达式

    @JvmStatic
    private val regEx_image = "<img[^>]*?>" // 定义HTML标签的正则表达式

    @JvmStatic
    private val regEx_space = "\\s+|\\t|\\r|\\n|&[a-z]{2,4};"//定义空格回车换行符

    @JvmStatic
    fun removeImgHtml(htmlStr: String?): String? {
        return if (htmlStr == null) null else removeHtml(
                htmlStr,
                arrayOf(regEx_script, regEx_style, regEx_image, regEx_space)
        )
    }

    /**
     * @param htmlStr
     * @return 删除Html标签
     */
    @JvmStatic
    @JvmOverloads
    fun removeHtml(htmlStr: String?, patterns: Array<String>? = null): String {
        var htmlStr = htmlStr ?: ""
        (patterns ?: arrayOf(regEx_script, regEx_style, regEx_html, regEx_space)).forEach {
            val pattern = Pattern.compile(it, Pattern.CASE_INSENSITIVE)
            val matcher = pattern.matcher(htmlStr)
            htmlStr = matcher.replaceAll("")
        }
        return htmlStr.trim { it <= ' ' } // 返回文本字符串
    }

    @JvmStatic
    fun getTextFromHtml(htmlStr: String?): String {
        var htmlStr = htmlStr ?: ""
        htmlStr = removeHtml(htmlStr)
        htmlStr = htmlStr.replace(" ".toRegex(), "")
        return htmlStr
    }


    /**
     * html 编码
     *
     * @param source
     * @return
     */
    @JvmStatic
    fun htmlEncode(source: String?): String {
        if (source == null) {
            return ""
        }
        var html = ""
        val buffer = StringBuffer()
        for (i in 0 until source.length) {
            val c = source[i]
            when (c) {
                '<' -> buffer.append("&lt;")
                '>' -> buffer.append("&gt;")
                '&' -> buffer.append("&amp;")
                '"' -> buffer.append("&quot;")
                ' ' -> buffer.append("&nbsp;")

                else -> buffer.append(c)
            }
        }
        html = buffer.toString()
        return html
    }


    /**
     * html 解码
     *
     * @param source
     * @return
     */
    @JvmStatic
    fun htmlDecode(source: String): String {
        var source = source
        if (TextUtils.isEmpty(source)) {
            return ""
        }
        source = source.replace("&lt;", "<")
        source = source.replace("&gt;", ">")
        source = source.replace("&amp;", "&")
        source = source.replace("&quot;", "\"")
        source = source.replace("&nbsp;", " ")
        source = source.replace("&ldquo;", "\"")
        source = source.replace("&rdquo;", "\"")

        return getTextFromHtml(source)
    }
}